const Koa = require('koa');
const app = new Koa();
const cors = require('koa-cors');
app.use(cors())

const router = require('@koa/router')()
const bodyParser = require('koa-bodyparser');

const global = require('./utils/mysql')

// 获取数据的接口
router.get('/list', async (ctx) => {
    let data = await global.query(`select * from address`)
    ctx.body = {
        code: 1,
        data,
        msg: '请求成功',
    }
})

// 添加的接口
router.post('/list/add', async (ctx) => {
    let { name, duty, defaults, voince, type, email } = ctx.request.body;

    if (defaults == 1) {
        let count = await global.query(`select * from address where defaults = 1`)
        if (count.length == 1) {
            let result = await global.query(`update address set defaults = 0 where defaults = 1`)
        }
    }

    let data = await global.query(`insert into address(name,duty,defaults,voince,type,email) values('${name}','${duty}',${defaults},${voince},'${type}','${email}')`);
    if (data.affectedRows == 1) {
        ctx.body = {
            code: 1,
            msg: '添加成功',
        }
    } else {
        ctx.body = {
            code: 0,
            msg: '添加失败',
        }
    }
})

// 获取某一条数据
router.get('/detail/:id', async (ctx) => {
    let { id } = ctx.params
    if (!id) {
        ctx.body = {
            code: 0,
            msg: '缺少参数'
        }
    }
    let result = await global.query(`select * from address where id = ${id}`)
    if (result.length > 0) {
        ctx.body = {
            code: 1,
            msg: '成功',
            data: result
        }
    }
})

// 修改的接口
router.post('/list/update', async (ctx) => {
    let { id, name, duty, defaults, type, email, voince } = ctx.request.body

    if (defaults == 1) {
        let count = await global.query(`select * from address where defaults = 1`)
        if (count.length == 1) {
            let result = await global.query(`update address set defaults = 0 where defaults = 1`)
        }
    }

    let data = await global.query(`update address set name='${name}',duty='${duty}',defaults=${defaults},type='${type}',email='${email}',voince=${voince} where id = ${id}`);
    if (data.affectedRows == 1) {
        ctx.body = {
            code: 1,
            msg: '更新成功'
        }
    } else {
        ctx.body = {
            code: 0,
            msg: '更新失败'
        }
    }
})

// 删除的接口
router.post('/list/del', async (ctx) => {
    let { id } = ctx.request.body;
    let sql = `delete from address where id = ${id}`
    let result = await global.query(sql)
    ctx.body = {
        code: 1,
        result,
        msg: "删除成功"
    }
})

app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());


app.listen(4000, () => {
    console.log("http://localhost:4000 启动成功");
});